package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @author zsk
 * @create 2022-03-22-17:58
 */
@RestController
public class UserController {

    @Autowired
    private UserManager userManager;

    // 保存用户
    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user) {
        return userManager.save(user); // 状态码200  ，请求体存用户id
    }

    // 查询用户
    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone) {
        return userManager.findByPhone(phone);
    }

    //首次登录获取验证码
    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String,String> param){
        //获取参数
        String phone = param.get("phone");

        //调用manager
        userManager.sendSms(phone);
    }


    //登录与验证码校验
    @PostMapping("/user/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map<String,String> param){
        //取出参数
        String phone = param.get("phone");
        String verificationCode = param.get("verificationCode");//验证码

        //调用manager
        return userManager.loginVerification(phone,verificationCode);

    }

    //首次登录补全信息
    @PostMapping("/user/loginReginfo")
    public void loginReginfo(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token){
        //调用manager
        userManager.loginReginfo(userInfo,token);

    }

    //首次登录完善用户头像信息
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public ResponseEntity loginReginfoHead(MultipartFile headPhoto,@RequestHeader("Authorization") String token) throws Exception {
        //调用manager
        return userManager.loginReginfoHead(headPhoto,token);
    }

    //根据id查询用户信息
    @GetMapping("/users")
    public ResponseEntity findById(Long userID,@RequestHeader("Authorization")String token){

        //判断userID
        if (userID != null){//根据前端id查询
            //调用manager
            return userManager.findById(userID);
        }else {//根据token里的userId查询
            User user = userManager.findUserByToken(token);
            //调用manager
            return userManager.findById(user.getId());
        }
    }

    //更新用户信息
    @PutMapping("/users")
    public void updateUserInfo(@RequestBody UserInfo userInfo){
        //调用manager
        userManager.updateUserInfo(userInfo);
    }
}
